#coding:utf-8
__author__ = 'yasin'

import time
from weisdk.parser import parse_user_msg
from weisdk.reply import TextReply, ArticlesReply, Article
from models import SubMessage

def dispatcher(account, xml_msg):
    msg = parse_user_msg(xml_msg)
    print msg.raw
    reply = None
    if msg.type == 'subscribe':
        sub_message = SubMessage.query.get(account.sub_message)
        reply = TextReply(target=msg.source, source=msg.target, time=time.time(), content=sub_message.message)
    if msg.type == 'text':
        if msg.content.find(u'a') >= 0:
            reply = ArticlesReply(target=msg.source, source=msg.target, time=time.time())
            article = Article(**{'title': 'fff',
                                 'description': 'qq',
                                 'img': 'http://img0.bdstatic.com/img/image/shouye/sysxsy-9400877587.jpg',
                                 'url': 'http://42.96.202.135/weihome/%s' % account.id,
                                 })
            reply.add_article(article)
        elif msg.content.find(u'1') >= 0:
            reply = TextReply(target=msg.source, source=msg.target, time=time.time(), content='1')
        else:
            reply = TextReply(target=msg.source, source=msg.target, time=time.time(), content='/:,@@')
    if reply:
        print reply.render()
        return reply.render()
    else:
        return ''